package com.adresvseti.wallpaperoid.helpers;

import java.util.List;

import com.adresvseti.wallpaperoid.constants.Settings;
import com.adresvseti.wallpaperoid.models.Wallpaper;
import com.adresvseti.wallpaperoid.services.DecodeResourceBitmapTask;
import com.adresvseti.wallpaperoid.services.IDecodeBitmapCallback;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class WallpaperImageAdapter extends BaseAdapter {

	private Context context;
	private List<Wallpaper> wallpapers;

	
	// Constructor
    public WallpaperImageAdapter(Context context, List<Wallpaper> wallpapers){
        this.context = context;
        this.wallpapers = wallpapers;
    }
 
    @Override
    public int getCount() {
        return wallpapers.size();
    }
 
    @Override
    public Object getItem(int position) {
        return wallpapers.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return wallpapers.get(position).id;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        
    	final ImageView imageView = new ImageView(context);
        
        final Wallpaper wallpaper = wallpapers.get(position);
        Bitmap bitmap = null;
        if (wallpaper.thumbBitmap == null) {
        	
        	// loading bitmap
        	DecodeResourceBitmapTask decodeTask = new DecodeResourceBitmapTask(context, Settings.THUMB_MAXWIDTH, Settings.THUMB_MAXHEIGHT, new IDecodeBitmapCallback() {
				
				@Override
				public void success(Bitmap result) {
					
					// caching
		        	wallpaper.thumbBitmap = result;
		        	
		        	// setting bitmap
		        	setViewBitmap(imageView, result);
				}
			});
        	
        	decodeTask.execute(wallpaper.thumbResId);
        	
        }
        else {
        	bitmap = wallpaper.thumbBitmap;
        }
        
        if (bitmap != null)
        {
        	setViewBitmap(imageView, bitmap);
        }
        
        return imageView;
    }
    
    private void setViewBitmap(ImageView imageView, Bitmap bitmap)
    {
    	imageView.setImageBitmap(bitmap);
    	imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    	imageView.setLayoutParams(new GridView.LayoutParams(Settings.THUMB_MAXWIDTH, Settings.THUMB_MAXHEIGHT));
    }
}
